<template>
  <view class="assessment-card">
    <!-- ✅ 优化：评估头部信息 -->
    <view class="assessment-header">
      <view class="header-left">
        <view class="date-time-group">
          <text class="assessment-date">{{ formatDate(assessment.assessment_date) }}</text>
          <text class="assessment-time">{{ formatTime(assessment.create_time) }}</text>
        </view>
        <!-- ✅ 新增：评估类型标识 -->
        <view class="type-badge" :class="assessment.assessment_type === 2 ? 'self-eval' : 'doctor-eval'">
          <text class="type-text">{{ assessment.assessment_type === 2 ? '🏃 患者自评' : '👨‍⚕️ 医生评估' }}</text>
        </view>
      </view>
      <view class="header-right">
        <!-- ✅ 完成进度 - 动态显示 -->
        <view class="progress-badge" :class="getProgressClass()">
          <text class="progress-text">{{ getCompletedCount() }}个量表</text>
        </view>
      </view>
    </view>
    
    <!-- ✅ 优化：只显示已填写的量表 -->
    <view class="scales-list">
      <!-- HAMD 抑郁量表 - 只在有数据时显示 -->
      <view v-if="assessment.hamd_status === 1" class="scale-item completed">
        <view class="scale-info">
          <text class="status-icon">✅</text>
          <view class="scale-details">
            <text class="scale-name">抑郁量表 HAMD</text>
            <text class="scale-score" :class="getScoreClassByValue('hamd', assessment.hamd_total)">
              {{ assessment.hamd_total }}分
            </text>
          </view>
        </view>
      </view>
      
      <!-- HAMA 焦虑量表 - 只在有数据时显示 -->
      <view v-if="assessment.hama_status === 1" class="scale-item completed">
        <view class="scale-info">
          <text class="status-icon">✅</text>
          <view class="scale-details">
            <text class="scale-name">焦虑量表 HAMA</text>
            <text class="scale-score" :class="getScoreClassByValue('hama', assessment.hama_total)">
              {{ assessment.hama_total }}分
            </text>
          </view>
        </view>
      </view>
      
      <!-- YMRS 狂躁量表 - 只在有数据时显示 -->
      <view v-if="assessment.ymrs_status === 1" class="scale-item completed">
        <view class="scale-info">
          <text class="status-icon">✅</text>
          <view class="scale-details">
            <text class="scale-name">狂躁量表 YMRS</text>
            <text class="scale-score" :class="getScoreClassByValue('ymrs', assessment.ymrs_total)">
              {{ assessment.ymrs_total }}分
            </text>
          </view>
        </view>
      </view>
      
      <!-- 如果一个量表都没填，显示提示 -->
      <view v-if="getCompletedCount() === 0" class="no-scales">
        <text class="no-scales-text">暂无量表数据</text>
      </view>
    </view>
    
    <!-- 评估备注 -->
    <view v-if="assessment.assessment_notes" class="assessment-notes">
      <text class="notes-label">备注：</text>
      <text class="notes-content">{{ assessment.assessment_notes }}</text>
    </view>
    
    <!-- 操作按钮 -->
    <view class="actions">
      <button class="action-btn primary" @click="viewFullDetails(assessment.id)">
        查看详情
      </button>
      <button class="action-btn export" @click="exportPDF(assessment.id)">
        📄 导出
      </button>
    </view>
  </view>
</template>

<script>
import { exportAssessmentPDF } from '../utils/api/doctor.js'

export default {
  name: 'AssessmentCard',
  props: {
    assessment: {
      type: Object,
      required: true
    }
  },
  
  methods: {
    // ✅ 优化：格式化日期（年月日）
    formatDate(dateString) {
      if (!dateString) return '';
      try {
        const date = new Date(dateString.replace(/-/g, '/'));
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (e) {
        return dateString;
      }
    },
    
    // ✅ 新增：格式化时间（时分秒）
    formatTime(dateTimeStr) {
      if (!dateTimeStr) return '';
      try {
        const date = new Date(dateTimeStr.replace(/-/g, '/'));
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
      } catch (e) {
        return '';
      }
    },
    
    // ✅ 计算完成的量表数量
    getCompletedCount() {
      if (!this.assessment) return 0;
      let count = 0;
      if (this.assessment.hamd_status === 1) count++;
      if (this.assessment.hama_status === 1) count++;
      if (this.assessment.ymrs_status === 1) count++;
      return count;
    },
    
    // 获取进度徽章样式类
    getProgressClass() {
      const count = this.getCompletedCount();
      if (count === 0) return 'progress-none';
      if (count === 3) return 'progress-full';
      return 'progress-partial';
    },
    
    // ✅ 新增：根据分数获取样式类
    getScoreClassByValue(scaleType, score) {
      if (scaleType === 'hamd') {
        if (score >= 24) return 'score-severe';
        if (score >= 17) return 'score-moderate';
        if (score >= 8) return 'score-mild';
        return 'score-normal';
      } else if (scaleType === 'hama') {
        if (score >= 29) return 'score-severe';
        if (score >= 21) return 'score-moderate';
        if (score >= 14) return 'score-mild';
        return 'score-normal';
      } else if (scaleType === 'ymrs') {
        if (score >= 20) return 'score-severe';
        if (score >= 12) return 'score-moderate';
        if (score >= 6) return 'score-mild';
        return 'score-normal';
      }
      return 'score-normal';
    },
    
    // 获取主要量表名称
    getPrimaryScaleName() {
      const scales = [
        { key: 'hamd', name: '抑郁量表', score: this.assessment.hamd_total, status: this.assessment.hamd_status },
        { key: 'hama', name: '焦虑量表', score: this.assessment.hama_total, status: this.assessment.hama_status },
        { key: 'ymrs', name: '躁狂量表', score: this.assessment.ymrs_total, status: this.assessment.ymrs_status }
      ];

      const completedScales = scales.filter(scale => scale.status === 1 && scale.score > 0);

      if (completedScales.length === 0) {
        return '无评估';
      }

      const primaryScale = completedScales.reduce((prev, current) =>
        (prev.score > current.score) ? prev : current
      );

      return primaryScale.name;
    },

    // 获取主要量表分数
    getPrimaryScaleScore() {
      const scales = [
        { key: 'hamd', name: '抑郁量表', score: this.assessment.hamd_total, status: this.assessment.hamd_status },
        { key: 'hama', name: '焦虑量表', score: this.assessment.hama_total, status: this.assessment.hama_status },
        { key: 'ymrs', name: '躁狂量表', score: this.assessment.ymrs_total, status: this.assessment.ymrs_status }
      ];

      const completedScales = scales.filter(scale => scale.status === 1 && scale.score > 0);

      if (completedScales.length === 0) {
        return 0;
      }

      const primaryScale = completedScales.reduce((prev, current) =>
        (prev.score > current.score) ? prev : current
      );

      return primaryScale.score;
    },

    // 获取主要量表样式类
    getPrimaryScaleClass() {
      const scales = [
        { key: 'hamd', name: '抑郁量表', score: this.assessment.hamd_total, status: this.assessment.hamd_status },
        { key: 'hama', name: '焦虑量表', score: this.assessment.hama_total, status: this.assessment.hama_status },
        { key: 'ymrs', name: '躁狂量表', score: this.assessment.ymrs_total, status: this.assessment.ymrs_status }
      ];

      const completedScales = scales.filter(scale => scale.status === 1 && scale.score > 0);

      if (completedScales.length === 0) {
        return 'score-normal';
      }

      const primaryScale = completedScales.reduce((prev, current) =>
        (prev.score > current.score) ? prev : current
      );

      return this.getScoreClassByValue(primaryScale.key, primaryScale.score);
    },

    getScoreClass(severity) {
      const classMap = {
        '正常': 'score-normal',
        '轻度': 'score-mild',
        '中度': 'score-moderate',
        '重度': 'score-severe'
      };
      return classMap[severity] || 'score-normal';
    },
    
    getSeverityClass(severity) {
      const classMap = {
        '正常': 'severity-normal',
        '轻度': 'severity-mild',
        '中度': 'severity-moderate',
        '重度': 'severity-severe'
      };
      return classMap[severity] || 'severity-normal';
    },
    
    viewScaleDetail(assessmentId, scaleType) {
      this.$emit('view-scale-detail', { assessmentId, scaleType });
    },
    
    viewFullDetails(assessmentId) {
      this.$emit('view-full-details', assessmentId);
    },
    
    createNewAssessment() {
      this.$emit('create-new-assessment');
    },
    
    // 导出PDF
    async exportPDF(assessmentId) {
      try {
        console.log('开始导出PDF，评估ID:', assessmentId);
        
        // 显示加载提示
        uni.showLoading({
          title: '正在生成PDF...',
          mask: true
        });
        
        // 调用导出API
        const filePath = await exportAssessmentPDF(assessmentId);
        
        console.log('PDF文件下载成功，路径:', filePath);
        uni.hideLoading();
        
        // 打开PDF文件
        uni.openDocument({
          filePath: filePath,
          fileType: 'pdf',
          showMenu: true,
          success: () => {
            console.log('PDF打开成功');
            uni.showToast({
              title: '导出成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: (err) => {
            console.error('PDF打开失败:', err);
            uni.showToast({
              title: 'PDF打开失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
        
      } catch (error) {
        uni.hideLoading();
        console.error('导出PDF失败:', error);
        uni.showToast({
          title: '导出失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
</script>

<style scoped>
.assessment-card {
  background: white;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
  transition: all 0.2s;
}

.assessment-card:active {
  transform: scale(0.98);
  box-shadow: 0 1rpx 4rpx rgba(0,0,0,0.15);
}

.assessment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.header-right {
  display: flex;
  align-items: center;
}

/* ✅ 新增：日期时间组 */
.date-time-group {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.assessment-date {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.assessment-time {
  font-size: 24rpx;
  color: #999;
}

.assessment-id {
  font-size: 24rpx;
  color: #999;
}

/* ✅ 新增：评估类型标识 */
.type-badge {
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
  display: inline-block;
  width: fit-content;
}

.type-badge.self-eval {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.type-badge.doctor-eval {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: #fff;
}

.type-text {
  font-size: 22rpx;
  font-weight: 500;
}

/* ✅ 完成进度徽章 */
.progress-badge {
  color: #fff;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  transition: all 0.3s ease;
}

.progress-badge.progress-none {
  background: linear-gradient(135deg, #95a5a6 0%, #bdc3c7 100%);
}

.progress-badge.progress-partial {
  background: linear-gradient(135deg, #f39c12 0%, #f1c40f 100%);
}

.progress-badge.progress-full {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.progress-text {
  font-weight: bold;
}

.scales-list {
  margin-bottom: 20rpx;
}

.scale-item {
  display: flex;
  align-items: center;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f8f8f8;
  transition: all 0.2s;
}

.scale-item:last-child {
  border-bottom: none;
}

.scale-item.completed {
  opacity: 1;
}

.scale-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

/* ✅ 状态图标 */
.status-icon {
  font-size: 32rpx;
}

.scale-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.scale-name {
  font-size: 26rpx;
  color: #333;
}

.scale-score {
  font-size: 28rpx;
  font-weight: bold;
}

/* 无量表数据提示 */
.no-scales {
  text-align: center;
  padding: 20rpx;
}

.no-scales-text {
  font-size: 26rpx;
  color: #999;
}

.scale-severity {
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
  margin-right: 10rpx;
}

.arrow {
  font-size: 24rpx;
  color: #ccc;
}

.assessment-notes {
  margin-bottom: 20rpx;
  padding: 15rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.notes-label {
  font-size: 24rpx;
  color: #666;
  font-weight: bold;
}

.notes-content {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
}

.actions {
  display: flex;
  gap: 12rpx;
}

.action-btn {
  flex: 1;
  padding: 14rpx 10rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  border: none;
  transition: all 0.2s;
  white-space: nowrap;
}

.action-btn.primary {
  background: #2DB5A3;
  color: white;
}

.action-btn.primary:active {
  background: #26a69a;
}

.action-btn.secondary {
  background: #f0f0f0;
  color: #666;
}

.action-btn.secondary:active {
  background: #e0e0e0;
}

.action-btn.export {
  background: rgba(255, 122, 69, 0.1);
  color: #FF7A45;
  font-weight: 500;
}

.action-btn.export:active {
  background: rgba(255, 122, 69, 0.2);
}

/* 分数颜色 */
.score-normal { color: #52c41a; }
.score-mild { color: #faad14; }
.score-moderate { color: #fa8c16; }
.score-severe { color: #f5222d; }

/* 严重程度颜色 */
.severity-normal { 
  background: #f6ffed; 
  color: #52c41a; 
}

.severity-mild { 
  background: #fffbe6; 
  color: #faad14; 
}

.severity-moderate { 
  background: #fff7e6; 
  color: #fa8c16; 
}

.severity-severe { 
  background: #fff2f0; 
  color: #f5222d; 
}
</style>
